﻿using BuyWithoutLoseMoney;
using BuyWithoutLoseMoney.Core.Models;
using BuyWithoutLoseMoney.Core.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;

namespace BuyWithoutLose.Areas.Admin.Controllers
{
    /// <summary>
    /// 管理员
    /// </summary>
    [Area("admin")]
    public class ManagementController : BaseAdminController
    {
        private readonly IRepository<LoginUser,int> _loginuserRepository;
        private readonly IRepository<Role,int> _roleRepository;
        private readonly IRepository<LoginUserRole, int> _loginUserRoleRepository;

        public ManagementController(IRepository<LoginUser,int> loginuserRepository
            , IRepository<Role, int> roleRepository, BuyWithoutLoseMoneyDBContext db
            , IRepository<LoginUserRole, int> loginUserRoleRepository) : base(db )
        {
            _loginuserRepository = loginuserRepository;
            _roleRepository = roleRepository;
            _loginUserRoleRepository = loginUserRoleRepository;
        }

        #region 管理员的列表，新建
        /// <summary>
        /// 管理员列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var loginuser = await _loginuserRepository.GetAllListAsync();
            var role = await _roleRepository.GetAllListAsync();
            ViewBag.role = role;
            return View(loginuser);
        }
        /// <summary>
        /// 管理列表的查询
        /// </summary>管理员名字
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Index(int page, int limit,string loginname, int roleid=0)
        {
            string cookieName = Request.Cookies["setCookieExpires"];
            var loginuser = _loginuserRepository.GetAll();
            var query = loginuser.Include(x=>x.Role).Where(x => true).Where(x=>x.LoginName!=cookieName);

            //搜索管理员姓名
            if (!string.IsNullOrEmpty(loginname))
            {
                query = query.Where(x =>x.LoginName.Contains(loginname));
            }
            var count = query.Count();
            var list = query.OrderBy(x => x.Id).Skip((page - 1) * limit).Take(limit).ToList()
               .Select(x => new
               {
                   id = x.Id,
                   loginname = x.LoginName,
                   //LoginPwd = x.LoginPwd,///密码不展示
                   phone = x.Phone,
                   eMail = x.EMail,
                   //role=x.Role
                });
            return Json(new { Code = 0, Msg = "", Data = list, Count = count });
        }
        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Create()
        {
            var loginname = await _loginuserRepository.GetAllListAsync();
            ViewBag.loginname = loginname;
            var role = await _roleRepository.GetAllListAsync();
            ViewBag.role = role;
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Create(LoginUser loginUser)
        {
            //news.CreateTime = DateTime.Now;
            if (ModelState.IsValid)
            {
                await _loginuserRepository.InsertAsync(loginUser);
                return Json(new { isSuccess = true, msg = "添加成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "添加失败，页面即将返回！" });
        }
        #endregion

        #region 角色添加

        /// <summary>
        /// 管理员修改角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Edit(int id)
        {
            var loginUser = _loginuserRepository.GetAll().FirstOrDefault(x => x.Id == id);
            //ViewBag.LoginUser = loginUser;
            var role= await _roleRepository.GetAllListAsync();
            ViewBag.Role = role;
            return View(loginUser);
        }
        [HttpPost]
        public async Task<IActionResult> Edit(LoginUserRole loginUserRole)
        {
            if (ModelState.IsValid)
            {
                await _loginUserRoleRepository.InsertAsync(loginUserRole);
                return Json(new { isSuccess = true, msg = "添加成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "添加失败，请重试！" });
        }
        #endregion
        #region 当前管理员拥有角色列表
        [HttpGet]
        public async Task<IActionResult> LoginUserRoleList(int id)
        {
            var loginUser = _loginuserRepository.GetAllList();
            var role = await _roleRepository.GetAllListAsync();
            ViewBag.Role = role;
            var logunUserRole = _loginUserRoleRepository.GetAllList();
            ViewBag.LoginUserRole = logunUserRole;
            ViewBag.Id = id;
            return View(loginUser);
        }
        #endregion
        #region 删除
        [HttpPost]
        public async Task<IActionResult> Del(int loginuserId,int roleId)
        {
            LoginUserRole p = new LoginUserRole() { LoginUserId = loginuserId,RoleId=roleId };
            if (ModelState.IsValid)
            {
                await _loginUserRoleRepository.DeleteAsync(p);
                return Json(new { isSuccess = true, msg = "删除成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "删除失败，请重试！" });
        }
        #endregion
    }
}
